package org.yelongframework.excel.data.collect.sheet.mode.fors.down;

import java.util.function.Function;

import org.yelongframework.excel.cell.ExcelCell;
import org.yelongframework.excel.data.SheetData;
import org.yelongframework.excel.data.SheetDatas;
import org.yelongframework.excel.data.collect.sheet.SheetDataCollectException;
import org.yelongframework.excel.row.ExcelRow;
import org.yelongframework.excel.sheet.ExcelSheet;

/**
 * 默认实现
 * 
 * @since 1.0.0
 */
public class DefaultDownForSheetDataCollector extends AbstractDownForSheetDataCollector {

	// ==================================================执行收集==================================================

	@Override
	protected SheetDatas doCollect(ExcelSheet excelSheet, DownForSheetDataCollectScheme sheetDataCollectScheme)
			throws SheetDataCollectException {
		int beginRowIndex = sheetDataCollectScheme.getBeginRowIndex();
		int beginColumnIndex = sheetDataCollectScheme.getBeginColumnIndex();
		int endColumnIndex = sheetDataCollectScheme.getEndColumnIndex();
		Integer forCount = sheetDataCollectScheme.getForCount();
		Function<ExcelRow, Boolean> endRowDeduceFunction = sheetDataCollectScheme.getEndRowDeduceFunction();
		SheetDatas sheetDatas = new SheetDatas(excelSheet.getSheetIndex());
		// 明确循环次数时
		if (null != forCount) {
			for (int i = beginRowIndex; i < beginRowIndex + forCount; i++) {
				ExcelRow excelRow = excelSheet.getRow(i);
				if (null == excelRow) {
					continue;
				}
				for (int j = beginColumnIndex; j <= endColumnIndex; j++) {
					ExcelCell excelCell = excelRow.getCell(j);
					if (null == excelCell) {
						continue;
					}
					sheetDatas.add(new SheetData(i, j, excelCell.getValueString()));
				}
			}
		} else if (null != endRowDeduceFunction) {
			int lastRowNum = excelSheet.getLastRowNum();
			for (int i = beginRowIndex; i <= lastRowNum; i++) {
				ExcelRow excelRow = excelSheet.getRow(i);
				if (null == excelRow) {
					continue;
				}
				if (endRowDeduceFunction.apply(excelRow) == true) {
					break;
				}
				for (int j = beginColumnIndex; j <= endColumnIndex; j++) {
					ExcelCell excelCell = excelRow.getCell(j);
					if (null == excelCell) {
						continue;
					}
					sheetDatas.add(new SheetData(i, j, excelCell.getValueString()));
				}
			}
		} else {
			int lastRowNum = excelSheet.getLastRowNum();
			for (int i = beginRowIndex; i <= lastRowNum; i++) {
				ExcelRow excelRow = excelSheet.getRow(i);
				if (null == excelRow) {
					continue;
				}
				for (int j = beginColumnIndex; j <= endColumnIndex; j++) {
					ExcelCell excelCell = excelRow.getCell(j);
					if (null == excelCell) {
						continue;
					}
					sheetDatas.add(new SheetData(i, j, excelCell.getValueString()));
				}
			}
		}
		return sheetDatas;
	}

}
